The do-while Loop
The do-while loop looks like this:
do
{
this ;
and this ;
and this ;
and this ;
} while ( this condition is true ) ;
There is a minor difference between the work
ing of while and do-while loops. This difference is the place where the condition is
tested. The while tests the condition before executing any of the statements within the while loop. As against this, the do-while
tests the condition after having executed the statements within the loop. Figure would clarify the execution of do-while loop still
further.
This means that do-while would execute its statements at least once, even if the condition fails for the first time. The while, onthe other hand will not execute its statements if the condition fails for the first time. This difference is brought about more clearly bythe following program.
main( )
{
while ( 4 < 1 )
printf ( "Hello there \n") ;
}
Here, since the condition fails the first time itself, the printf( ) will not get executed at all. Let's now write the same program using a
do-while loop.
main( )
{
do
{
printf ( "Hello there \n") ;
} while ( 4 < 1 ) ;
}
In this program the printf( ) would be executed once, since first the body of the loop is executed and then the condition is tested. There are some occasions when we want to execute a loop at least once no matter what.
Note:- above information taken from "Let's C" book.